package cn.edu.hfut.dmic.util;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

/**
 * 下载文件
 */
public class FileDownload {

	/**
	 * @param response 
	 * @param filePath		//文件完整路径(包括文件名和扩展名)
	 * @param fileName		//下载后看到的文件名
	 * @return  文件名
	 */
//	public static void fileDownload(final HttpServletResponse response, String filePath, String fileName) throws Exception{
//
//		byte[] data = FileUtil.toByteArray2(filePath);
//	    fileName = URLEncoder.encode(fileName, "UTF-8");
//
//	    response.reset();
//	    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
//	    response.addHeader("Content-Length", "" + data.length);
//	    response.setContentType("application/octet-stream;charset=UTF-8");
//	    OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
//	    outputStream.write(data);
//	    outputStream.flush();
//	    outputStream.close();
//	    response.flushBuffer();
//
//	}
	/**

	 * TODO 下载文件到本地
	 * @author nadim
	 * @date Sep 11, 2015 11:45:31 AM
	 * @param fileUrl 远程地址
	 * @param fileLocal 本地路径
	 * @throws Exception
	 */
	public static boolean downloadFile(String fileUrl,String fileLocal) throws Exception {
		boolean flag=false;
		URL url = new URL(fileUrl);
		HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
		urlCon.setConnectTimeout(6000);
		urlCon.setReadTimeout(6000);
		int code = urlCon.getResponseCode();
		if (code != HttpURLConnection.HTTP_OK) {
			throw new Exception("文件读取失败");
		}
		//读文件流
		DataInputStream in = new DataInputStream(urlCon.getInputStream());
		FileOutputStream fileOutputStream = new FileOutputStream(fileLocal);
		fileOutputStream.getFD();
		DataOutputStream out = new DataOutputStream(fileOutputStream);
//		out.
		byte[] buffer = new byte[2048];
		int count = 0;
		while ((count = in.read(buffer)) > 0) {
			out.write(buffer, 0, count);
		}
		try {
			if(out!=null) {
				out.close();
			}
			if(in!=null) {
				in.close();
			}
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
		flag=true;
		return flag;
	}

}
